//获取富文本内的图片url地址
export function getImgSrc(richtext, num = 3) {
  let imgList = [];
  richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
    // match => 查找的元素
    // capture => 查找元素的下标
    imgList.push(capture);
  });
  imgList = imgList.slice(0, num)
  return imgList;
}

// 超过一小时 重新请求高德api，反之从浏览器中获取缓存
export function getProvince() {
  return new Promise((resolve, reject) => {
    let history_city = uni.getStorageSync("history_city")
    if (history_city) {
      // 对比时间戳 如果超过一小时，则重新请求地址，；不超过则缓存中获取
      if (Date.now() - history_city.time > 1000 * 60 * 60) {
        getIp().then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      } else {
        resolve(history_city.city)
      }
    } else {
      getIp().then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    }
  })
}
// 高德iap获取用户地址
function getIp() {
  // wx小程序：903ff173a0eeece73aa544d25ba262cb
  // web端：f84fdd0a8f527ea5be4c0458e52a86f9
  return new Promise((resolve, reject) => {
    uni.request({
      url: "https://restapi.amap.com/v3/ip?key=f84fdd0a8f527ea5be4c0458e52a86f9",
      success: res => {
        console.log('tool')
        console.log(res)
        let str = ''
        typeof(res.data.province) == "string" ? str = res.data.province: str = '未知'
        resolve(str)
        let obj = {
          city: str,
          time: Date.now()
        }
        uni.setStorageSync('history_city', obj)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}
// 判断用户是否登录
import pageJson from "@/pages.json"
export function goLoginPage() {
  uni.showModal({
    title: "未登录 是否去登录？",
    success(res) {
      console.log(pageJson.uniIdRouter)
      if (res.confirm) {
        uni.navigateTo({
          url: "/" + pageJson.uniIdRouter.loginPage
        })

      }
    }
  })
}
// 点赞防抖
import {
  store
} from "@/uni_modules/uni-id-pages/common/store.js"
// 导入工具函数 阅读量加1
const utilsObj = uniCloud.importObject("utilsObj", {
  customUI: true // 取消自动展示的交互提示界面
})
const db = uniCloud.database()
let art_timer = null
let art_state = true
let art_count = 0
export function on_like(uToast) {
  if (!store.hasLogin) {
    goLoginPage()
    return false
  }
  clearTimeout(art_timer)
  if (art_state) {
    art_state = false
    art_count = 0
    return true
  }
  if (art_count > 0) {
    console.log("请不要连续点赞")
    uToast.value.show({
      title: '请不要连续点赞',
      type: 'warning '
    })
    art_count = 0
  }
  art_count++
  art_timer = setTimeout(() => {
    art_state = true
  }, 868)
  return true
}

// 点赞事件
export async function artLike(art_id) {
  // 查询点赞数量
  const count = await db.collection("pyq_like")
    .where(`article_id == "${art_id}" && user_id ==$cloudEnv_uid`)
    .count()
  // $cloudEnv_uid ==> 用户uid，依赖uni-id
  // 判断是否存在点赞 存在就删除点赞，文章表点赞数减一
  if (count.result.total) {
    db.collection("pyq_like").where(`article_id == "${art_id}" && user_id ==$cloudEnv_uid`)
      .remove()
    utilsObj.operation("pyq_article", "like_count", art_id, -1).then(res => {})
  } else {
    //判断是否存在点赞  不存在就记录点赞 文章表点赞数加一
    db.collection("pyq_like").add({
      article_id: art_id
    })
    utilsObj.operation("pyq_article", "like_count", art_id, 1).then(res => {})
  }
}